using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace AndyPike.Commons.Extensions
{
    public static class StringExtensions
    {
        public static bool IsValidEmailFormat(this string input)
        {
            if(string.IsNullOrEmpty(input))
                return false;
            
            return new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,6}$").IsMatch(input);
        }

        public static bool IsGuid(this string input)
        {
            if (string.IsNullOrEmpty(input))
                return false;

            try
            {
                var guid = new Guid(input);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }

        public static string ToMD5(this string input)
        {
            GuardAgainst.ArgumentNull(input, "input");

            if (input == string.Empty) return string.Empty;

            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hash = md5.ComputeHash(Encoding.ASCII.GetBytes(input));

            var hashAsHex = new StringBuilder();
            Array.ForEach(hash, b => hashAsHex.Append(b.ToString("X2")));

            return hashAsHex.ToString();
        }
    }
}